/**
 * Created on 18 nov. 2011 at 14:10:38 by HozakaN
 */
package fr.castorhoz.isi_connectivity_widget.widget_configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import fr.castorhoz.isi_connectivity_widget.AndroidTools;
import fr.castorhoz.isi_connectivity_widget.ConnButton;
import fr.castorhoz.isi_connectivity_widget.ConnWidget;
import fr.castorhoz.isi_connectivity_widget.R;
import fr.castorhoz.isi_connectivity_widget.bluetooth_widget.BluetoothBroadcastReceiver;
import fr.castorhoz.isi_connectivity_widget.database.DBAdapter;
import fr.castorhoz.isi_connectivity_widget.gps_widget.GPSBroadcastReceiver;
import fr.castorhoz.isi_connectivity_widget.mobiledata_widget.MobileDataBroadcastReceiver;
import fr.castorhoz.isi_connectivity_widget.roaming_widget.RoamingBroadcastReceiver;
import fr.castorhoz.isi_connectivity_widget.widget_configuration.custom_adapters.WidgetListAdapter;
import fr.castorhoz.isi_connectivity_widget.wifi_widget.WifiBroadcastReceiver;

/**
 * @author HozakaN
 *
 */
public class WidgetConfiguration extends Activity implements Observer {
		
	/**
	 * Action data sent to the WidgetConfigurationClass so it adds the other datas into the selected widgets list and update the visualisation view
	 */
	public static final String ADD_WIDGET = "addWidget";
	
	/**
	 * Action data sent to the WidgetConfigurationClass so it removes the other datas into the selected widgets list and update the visualisation view
	 */
	public static final String REMOVE_WIDGET = "removeWidget";
	
	/**
	 * Name of the SharedPreferences associated to the application
	 */
	public static final String ISI_CONNECTIVITY_WIDGET_PREFERENCES_PREFIX = "fr.castorhoz.isi_connectivity_widget_preferences";
	
	/**
	 * Name of the SharedPreferences associated to the application
	 */
	public static final String SEPARATOR = "_";
	
	/**
	 * List of existing widgets. Taken from the enumeratino ConnButton.widgets
	 */
	private List<ConnButton.widgets> widgets = new ArrayList<ConnButton.widgets>();
	
	/**
	 * Widgets selected by the user. There is no use of a Set since the user cannot double select a widget.
	 */
	private List<String> selectedWidgets = new ArrayList<String>();
	
	/**
	 * The list adapter for the preferences view
	 */
	private WidgetListAdapter wla;
	
	/**
	 * Images List of the widgets selected by the user, so they can be displayed into the visualisation layout
	 */
	private List<ImageView> images = new ArrayList<ImageView>();
	
	/**
	 * Layout in which appear widgets selected
	 */
	private LinearLayout visualisationLayout;

	/**
	 * widgetId for the widget that launched this activity
	 */
	private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	private DBAdapter dbAdapter;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.widget_configuration_layout);
		
        visualisationLayout = (LinearLayout) findViewById(R.id.visualisation_layout);
        visualisationLayout.setGravity(Gravity.CENTER); //don't fucking know why this param doesn't work in the xml layout file
        
        dbAdapter = new DBAdapter(getApplicationContext());
        
        /*
         * Configuration of the action when clicking the Save Button
         */
        ((Button)findViewById(R.id.saveConfigButton)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (saveConfig()) {
					
					Context context = WidgetConfiguration.this;
					AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

					ConnWidget.updateAppWidget(context, appWidgetManager, appWidgetId);
					
					Log.w(this.getClass().getName(), "update of widget "+appWidgetId+" asked");
					
					Intent resultValue = new Intent();
					resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
					setResult(RESULT_OK, resultValue);
					closeActivity();
				} else {
					AndroidTools.afficherErreur(getApplicationContext(), "Sauvegarde incomplete");
				}
			}
		});
        
        /*
         * Configuration of the action when clicking the Cancel Button
         */
        ((Button)findViewById(R.id.cancelConfigButton)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.i(this.getClass().getName(), "configuration left");
				closeActivity();
			}
		});
        
        /*
         * obtain the appWidgetId for the widget that launched this activity
         */
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            appWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        
        /*
         * if the id is null, finish the activity
         */
        if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }
        
        Log.i(this.getClass().getName(), "widget calling : "+appWidgetId);
        

		/*
		 * Finding widgets
		 */
		for (ConnButton.widgets widget : ConnButton.widgets.values()) {
			widgets.add(widget);
		}
		
		wla = new WidgetListAdapter(this, getApplicationContext(), widgets);
		ListView lv = (ListView)findViewById(R.id.widgetListView);
		lv.setAdapter(wla);
	}

	/**
	 * Saves choices made by the user
	 * @return
	 */
	private boolean saveConfig() {
		SharedPreferences sp = getSharedPreferences(ISI_CONNECTIVITY_WIDGET_PREFERENCES_PREFIX, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();

		/*
		 * The key is the widget name, and the value its position into the list
		 * The position is the one choosen by the user since the list order is kept
		 */
		dbAdapter.open();
		StringBuffer sb = new StringBuffer();
		for (String widgetName : selectedWidgets) {
			sb.append(widgetName).append(SEPARATOR);
			listenBroadcastReceiver(widgetName);
			dbAdapter.insertAppWidgetWidgets(widgetName, appWidgetId);
		}
		dbAdapter.close();
		
		Log.i(this.getClass().getName(), selectedWidgets.size()+" widgets inserted in base");
		editor.putString(ISI_CONNECTIVITY_WIDGET_PREFERENCES_PREFIX+appWidgetId, sb.substring(0, sb.lastIndexOf(SEPARATOR)));
		return editor.commit();
	}

	private void listenBroadcastReceiver(String widgetName) {
		switch (ConnButton.widgets.valueOf(widgetName)) {
		case bluetoohWidget:
			BluetoothBroadcastReceiver.addAppWidget(appWidgetId);
			break;
		case gpsWidget:
			GPSBroadcastReceiver.addAppWidget(appWidgetId);
			break;
		case mobileDataWidget:
			MobileDataBroadcastReceiver.addAppWidget(appWidgetId);
			break;
		case roamingWidget:
			RoamingBroadcastReceiver.addAppWidget(appWidgetId);
			break;
		case wifiWidget:
			WifiBroadcastReceiver.addAppWidget(appWidgetId);
			break;

		default:
			break;
		}
	}

	/**
	 * Closes the activity, and all what must be closed into it
	 */
	private void closeActivity() {
		finish();
	}

	
	/* (non-Javadoc)
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	public void update(Observable observable, Object data) {
		if (data instanceof String[]) {
			if (((String[])data)[0].equals(ADD_WIDGET)) {
				addWidget(((String[])data)[1]);
			} else {
				//The only other action at the time is REMOVE_WIDGET
				removeWidget(((String[])data)[1]);
			}
		}
	}

	/**
	 * Removes the widget from the selected widgets List and updates the visualisation layout
	 */
	private void removeWidget(String widgetName) {
		for (ImageView iv : images) {
			if (iv.getTag().equals(widgetName)) {
				visualisationLayout.removeView(iv);
				images.remove(iv);
				selectedWidgets.remove(widgetName);
				break;
			}
		}
	}

	/**
	 * Adds the widget to the selected widgets List and updates the visualisation layout
	 * @param widgetName
	 */
	private void addWidget(String widgetName) {
		ImageView iv = new ImageView(getApplicationContext());
		int drawableId = ConnButton.widgets.getAdaptedDrawableId(widgetName);
		iv.setImageResource(drawableId);
		iv.setTag(widgetName);
		LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		iv.setLayoutParams(lp);
		
		visualisationLayout.addView(iv);
		images.add(iv);
		selectedWidgets.add(widgetName);
	}

}
